package model

import "go-devops/dao"

type TaskHis struct {
	Id         int64  `json:"id" gorm:"primaryKey"`
	BatchId    int64  `json:"batchId"`
	TaskId     string `json:"taskId"`
	Status     string `json:"status"`
	GitMsg     string `json:"gitMsg"`
	GitBranch  string `json:"gitBranch"`
	OptUser    string `json:"optUser"`
	LogFile    string `json:"logFile"`
	CreateTime string `json:"createTime"`
}

func (TaskHis) TableName() string {
	return "task_his"
}

func QueryTaskHisByTaskId(taskId string) (taskHis *TaskHis, err error) {
	if err := dao.DB.Last(&taskHis, "task_id = ?", taskId).Error; err != nil {
		return nil, err
	}
	return taskHis, nil
}

func AddTaskHis(taskHis *TaskHis) (err error) {
	return dao.DB.Save(&taskHis).Error
}

func UpdateTaskHisStatus(taskHis *TaskHis) (err error) {
	return dao.DB.Model(&TaskHis{}).Where("batch_id = ? and task_id = ?", taskHis.BatchId, taskHis.TaskId).Update("status", taskHis.Status).Error
}

func UpdateTaskHisGitMsg(taskHis *TaskHis) (err error) {
	db := dao.DB.Model(&TaskHis{})
	db = db.Where("batch_id = ? and task_id = ?", taskHis.BatchId, taskHis.TaskId)
	return db.Updates(map[string]interface{}{"git_msg": taskHis.GitMsg, "git_branch": taskHis.GitBranch}).Error
}

func QueryPageTaskHis(offset int, limit int, taskId string) (list []*TaskHis, total int64, err error) {
	db := dao.DB.Model(&TaskHis{}).Where("task_id = ?", taskId).Count(&total).Offset(offset).Limit(limit)
	db.Order("id desc").Find(&list)
	return list, total, db.Error
}

func QueryTaskHisByBatchId(batchId int64, taskId string) (taskHis *TaskHis, err error) {
	if err := dao.DB.Model(&TaskHis{}).Where("batch_id = ? and task_id = ?", batchId, taskId).First(&taskHis).Error; err != nil {
		return nil, err
	}
	return taskHis, nil
}
